package cn.wise.rocketmq.producerdemo1.api._02_producer_type;

import io.netty.util.Timeout;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class AyncProducer {
    public static void main(String[] args) throws Exception {
        //创建一个生产者对象
        DefaultMQProducer producer = new DefaultMQProducer("wise-producer");
        //2 设置nameserver的地址
        producer.setNamesrvAddr("192.168.147.128:9876;192.168.147.129:9876");
        //启动生产者
        producer.start();
        CountDownLatch count = new CountDownLatch(100);
        //创建一个message对象
        for (int i = 0; i < 100; i++) {
            //同步的方式
            Message message = new Message("02-producer_type", "hello,rocketmq".getBytes("utf-8"));
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送成功");
                    //计数器减1
                    count.countDown();
                }

                @Override
                public void onException(Throwable e) {
                    System.out.println("发送失败");
                    //计数器减1
                    count.countDown();
                }
            });
        }
        //睡一下  因为异步会返回数据才知道是成功还是失败 这里需要时间返回校对 不然就会一直提示失败
        //TimeUnit.SECONDS.sleep(3);
        //需要确保所有的异步回调信息才关闭 让线程阻塞 await=0才对放行
        count.await();
        //关闭生产者
        producer.shutdown();
    }
}
